from django.shortcuts import render
from django import http
from django.views import View
from meiduo_mall.utils.response_code import RETCODE
from alipay import AliPay
from django.conf import settings
import os
from orders.models import OrderInfo
from .models import Payment


class GetUrlView(View):
    def get(self, request, order_id):
        # 验证订单编号
        try:
            order = OrderInfo.objects.get(pk=order_id)
        except:
            return http.Http404('订单编号无效')
        # 创建支付宝对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,
            app_private_key_path=os.path.join(settings.BASE_DIR, 'libs/alipay/app_private_key.pem'),
            alipay_public_key_path=os.path.join(settings.BASE_DIR, 'libs/alipay/alipay_public_key.pem'),
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )
        # 生成支付的参数
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            subject='美多商城-订单支付',
            return_url=settings.ALIPAY_RETURN_URL
        )
        # 拼接最终的支付地址
        alipay_url = settings.ALIPAY_URL + '?' + order_string
        # 响应
        return http.JsonResponse({
            'code': RETCODE.OK,
            'errmsg': 'OK',
            'alipay_url': alipay_url
        })


class AliPayStatusView(View):
    def get(self,request):
        # 接收支付宝返回的参数
        data=request.GET.dict()
        sign=data.pop('sign')
        # 验证是否支付成功
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,
            app_private_key_path=os.path.join(settings.BASE_DIR, 'libs/alipay/app_private_key.pem'),
            alipay_public_key_path=os.path.join(settings.BASE_DIR, 'libs/alipay/alipay_public_key.pem'),
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )
        success = alipay.verify(data,sign)
        # 支付成功后，修改订单状态

        if not success:
            # 支付失败，提示信息
            return http.HttpResponseBadRequest('支付失败请重新支付')

        # 保存支付宝流水号，
        # 修改订单为待发货
        order_id=data.get('out_trade_no')
        trade_no=data.get('trade_no')
        Payment.objects.create(
            order_id=order_id,
            trade_id=trade_no
        )
        OrderInfo.objects.filter(pk=order_id).update(status=4)

        context={
            'trade_no':data.get('trade_no')
        }


        return render(request,'pay_success.html',context)


